/*
 * Copyright 2024 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.pajamas.starter.integration.module.async;

import org.pajamas.starter.core.util.VmUtils;
import org.pajamas.starter.integration.spring.bean.BeanConstants;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.concurrent.Executor;

/**
 * @author william
 * @since 2024/1/15
 */
@ConditionalOnProperty(prefix = "org.pajamas.starter.async", value = "enabled", havingValue = "true", matchIfMissing =
        true)
@EnableAsync(proxyTargetClass = true)
public class PajamasAsyncAutoConfiguration {
    @ConditionalOnProperty(prefix = "org.pajamas.starter.async", value = "executor", havingValue =
            "true", matchIfMissing = true)
    @Order(BeanConstants.ORDER_LATEST_SECOND)
    @Bean
    public TaskExecutorCustomizer pajamasTaskExecutorCustomizer() {
        return taskExecutor -> {
            int cores = VmUtils.getRuntimeCorsNumber();
            int recommendedCors = cores + 1;
            taskExecutor.setThreadNamePrefix("PAJAMAS-ASYNC-TASK-");
            taskExecutor.setCorePoolSize(recommendedCors);
            taskExecutor.setMaxPoolSize(2 * recommendedCors);
            taskExecutor.setQueueCapacity(Integer.MAX_VALUE);
            taskExecutor.setKeepAliveSeconds(60);
            taskExecutor.setAllowCoreThreadTimeOut(false);
        };
    }

    @ConditionalOnProperty(prefix = "org.pajamas.starter.async", value = "exceptionHandler", havingValue =
            "true", matchIfMissing = true)
    @ConditionalOnMissingBean(AsyncConfigurer.class)
    @Bean
    public PajamasAsyncConfigurer pajamasAsyncConfigurer(@Qualifier(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME) Executor executor) {
        return new PajamasAsyncConfigurer(executor);
    }

    public static class PajamasAsyncConfigurer extends AsyncConfigurerSupport {
        private final Executor executor;

        public PajamasAsyncConfigurer(Executor executor) {
            this.executor = executor;
        }

        @Override
        public Executor getAsyncExecutor() {
            return this.executor;
        }

        @Override
        public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
            return (ex, method, params) -> {
                throw new PajamasAsyncRunException(ex);
            };
        }
    }
}
